import { ref } from 'vue'
import { useToggle } from '@vueuse/core'
import { useMutation } from '@tanstack/vue-query'
import type { TableColumnData } from '@arco-design/web-vue'

import {
  ApiImportStudent,
  KeyApiImportStudent,
  SearchUserKeyPrefix,
  userMessage
} from '@/apis/user'
import { useFetchMessage } from '@/composables/useFetchMessage'
import { invalidateQueries } from '@/apis/client'

export type Student = {
  username: string
  name: string
  password: string
}

export function useStudentImport() {
  const columns = [
    {
      title: '学号',
      dataIndex: 'username'
    },
    {
      title: '姓名',
      dataIndex: 'name'
    },
    {
      title: '默认密码',
      dataIndex: 'password'
    }
  ] as const satisfies TableColumnData[]

  const [modalVisible, toggle] = useToggle()

  const { showMessage } = useFetchMessage([userMessage])
  const { mutate, isPending } = useMutation({
    mutationFn: ApiImportStudent,
    mutationKey: KeyApiImportStudent,
    onSettled(data, error) {
      showMessage(data?.code ?? error?.data?.code)
    },
    onSuccess() {
      invalidateQueries(SearchUserKeyPrefix)
      toggle(false)
    }
  })

  const students = ref<Student[]>([])
  const preHandleStudents = (importedStudents: Student[]) => {
    students.value = importedStudents
    toggle(true)
  }

  const handleUpload = async () => {
    mutate(students.value)
  }

  return {
    columns,
    students,
    modalVisible,
    isPending,
    toggleVisible: (value?: boolean | undefined) => {
      if (isPending.value) return
      return toggle(value)
    },
    handleUpload,
    preHandleStudents
  }
}
